package com.cube.share.jackson.deserializer;

import com.cube.share.jackson.annotation.SearchEscape;
import com.cube.share.jackson.util.EscapeUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.deser.std.StringDeserializer;

import java.io.IOException;

/**
 * @author poker.li
 * @date 2021/10/26 14:15
 */
public class SearchEscapeDeserializer extends StringDeserializer implements ContextualDeserializer {

    private static final long serialVersionUID = -2278078159584542112L;

    private final char[] needsToEscape;

    public SearchEscapeDeserializer(char[] needsToEscape) {
        super();
        this.needsToEscape = needsToEscape;
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext context, BeanProperty property) {
        final SearchEscape searchEscape = property.getAnnotation(SearchEscape.class);
        if (searchEscape == null) {
            return this;
        }
        return new SearchEscapeDeserializer(searchEscape.needsToEscape());
    }

    @Override
    public String deserialize(JsonParser p, DeserializationContext context) throws IOException {
        final String value = super.deserialize(p, context);
        return EscapeUtil.escape(value, needsToEscape);
    }

}
